var path, curPos, max;
var count = 0;
var grow = true;
var raster;


function onFrame(event) {
    if (grow) {
        if (raster && (view.center - curPos).length < max) {
            for (var i = 0, l = count / 36 + 1; i < l; i++) {
                growSpiral();
            }
            path.smooth();
        } else {
            grow = false;
        }
    }
}

function growSpiral() {
        count++;
        var vector = new Point({
            angle: count * 5,
            length: count / 23 / 4
        });
        var rot = vector.rotate(90);
        var color = raster.getAverageColor(curPos + vector / 2);
        var value = color ? (color.gray) * 4.2 : 0;
        rot.length = Math.max(value, 0.2);
        var pos = curPos + vector;
        path.add(curPos + vector - rot);
        path.insert(0, curPos + vector + rot);
        curPos += vector;
}

function resetSpiral() {
    grow = true;

    // Transform the raster, so it fills the view:
    raster.fitBounds(view.bounds);

    if (path)
        path.remove();
    
    curPos = view.center;
    count = 0;
    path = new Path();
    path.fillColor = 'black';
    path.closed = true;

    curPos = view.center;
    max = Math.min(raster.bounds.width, raster.bounds.height) * 0.5;
}

function onResize() {
    text.remove();
    if (count > 0)
        resetSpiral();
}

function onKeyDown(event) {
    if (event.key == 'space') {
        path.selected = !path.selected;
    }
}

function onDocumentDrag(event) {
    event.preventDefault();
}

function onDocumentDrop(event) {
    event.preventDefault();

    var file = event.dataTransfer.files[0];
    alert(file);
    var reader = new FileReader();

    reader.onload = function ( event ) {
        var image = document.createElement('img');
        image.onload = function () {
            raster = new Raster(image);
            raster.remove();
            resetSpiral();
        };
        image.src = event.target.result;
    };
    reader.readAsDataURL(file);
}

DomEvent.add(document, {
    drop: onDocumentDrop,
    dragover: onDocumentDrag,
    dragleave: onDocumentDrag
});